package com.example.jdk8.threads;

import java.util.concurrent.*;

public class ThreadByExecutor {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 使用executor 创建线程
        handleExecutorsByRunnable();
        // 使用Callable 创建线程
        handleExecutorsByCallable();
    }

    /**
     * 使用callable 创建线程
     *
     * @throws ExecutionException   ExecutionException
     * @throws InterruptedException InterruptedException
     */
    private static void handleExecutorsByCallable() throws ExecutionException, InterruptedException {
        Callable<Integer> task = () -> {
            try {
                TimeUnit.SECONDS.sleep(1);
                return 123;
            } catch (InterruptedException e) {
                throw new RuntimeException("task interrupted", e);
            }
        };
        ExecutorService ex = Executors.newFixedThreadPool(1);
        Future<Integer> future = ex.submit(task);

        System.out.println("future done? " + future.isDone());

        Integer result = future.get();

        System.out.println("future done? " + future.isDone());
        System.out.print("result: " + result);
    }

    /**
     * 处理单线程 Runnable 的线程
     */
    private static void handleExecutorsByRunnable() {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(() -> {
            String name = Thread.currentThread().getName();
            System.out.println("Hello Executors: " + name);
        });

        // 终止线程运行
        try {
            System.out.println("attempt to shutdown executor");
            executor.shutdown();
            executor.awaitTermination(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            System.out.println("tasks interrupted!");
        } finally {
            if (!executor.isTerminated()) {
                System.out.println("cancel non-finished tasks");
            }
            executor.shutdownNow();
            System.out.println("shutdown finished");
        }
    }
}
